// App.tsx - 根组件（包含全局状态）
import * as React from 'react';
import { createContext, useContext, useEffect, useState } from 'react';
// import { Outlet } from 'react-router-dom';
import { useThemeStore } from './stores/themeStore';

// 全局状态类型
interface AppState {
  darkMode: boolean;
  currentConnection: string | null;
  toggleDarkMode: () => void;
  setCurrentConnection: (name: string | null) => void;
}

// 创建 Context
export const AppContext = createContext<AppState | null>(null);

// Hook
export const useApp = () => {
  const context = useContext(AppContext);
  if (!context) throw new Error('useApp must be used within AppProvider');
  return context;
};

// Provider 组件
export const AppProvider: React.FC<{ children: any }> = ({ children }) => {
  const { darkMode, toggleTheme, setDarkMode } = useThemeStore();
  const [currentConnection, setCurrentConnection] = useState<string | null>(() => {
    return localStorage.getItem('currentConnection');
  });

  // 初始化主题
  useEffect(() => {
    setDarkMode(darkMode);
  }, []);

  // 持久化连接设置
  useEffect(() => {
    if (currentConnection) {
      localStorage.setItem('currentConnection', currentConnection);
    } else {
      localStorage.removeItem('currentConnection');
    }
  }, [currentConnection]);

  const value: AppState = {
    darkMode,
    currentConnection,
    toggleDarkMode: toggleTheme,
    setCurrentConnection,
  };

  return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
};
